import {Button, Col, Input, message, Modal, Popconfirm, Row} from "antd";
import React, {useCallback, useContext, useEffect, useState} from "react";
import TextArea from "antd/es/input/TextArea.js";
import {hostContext} from "../../store/commonContext.jsx";
import cookie from "js-cookie";
import axios from "axios";

const UserModal = ({
                       visible,
                       onCancel,
                       user,
                   }) => {

    const host = useContext(hostContext)
    const token = cookie.get('access_token')
    const requestHeader = {headers: {'Authorization': 'Bearer ' + token}}

    const modalItemStyle = {
        display: 'flex',
        alignItems: 'center',
        gap: 8,
        marginTop: 8,
        marginBottom: 4,
        width: '100%'
    }

    // 修改后的状态初始化
    const [editUser, setEditUser] = useState({
        userId: user.userId,
        nickName: user.nickName || '',
        email: user.email || '',
        signature: user.signature || ''
    })

    const [editDate, setEditDate] = useState({
        year: user.year,
        monthS: user.monthS,
        dayS: user.dayS
    })

    // 添加 useEffect 同步最新数据
    useEffect(() => {
        setEditUser({
            userId: user.userId,
            nickName: user.nickName || '',
            email: user.email || '',
            signature: user.signature || ''
        })
        setEditDate({
            year: user.year,
            monthS: user.monthS,
            dayS: user.dayS
        })
    }, [user]) // 当 user 更新时同步状态

    const handleInputChange = (field) => (e) => {
        setEditUser(prev => ({
            ...prev,
            [field]: e.target.value
        }));
    };
    const handleDateChange = (field) => (e) => {
        setEditDate(prev => ({
            ...prev,
            [field]: e.target.value
        }));
    };

    const onConfirm = async () => {
        // 确保携带最新状态
        const payload = {
            ...editUser,
            birthday: editDate.year + '-' + editDate.monthS + '-' + editDate.dayS
        };
        const response = await axios.post(`${host}/oauth/self/update`, payload, requestHeader)
        if (response.status === 200) {
            message.success('更新成功~')
        }
        await setEditUser({})
        await setEditDate({})
        setTimeout(() => location.reload(), 500)
    }

    const onBack = () => {
        onCancel()
        setEditUser(user)
    }

    return (
        <Modal
            title="个人信息"
            visible={visible}
            onCancel={onCancel}
            style={{maxWidth: 400}}
            maskClosable={false} //不允许点击外部关闭
            keyboard={false} //不允许ESC关闭
            closable={false} //不允许右上角x关闭
            footer={[
                <Button key="back"
                        onClick={onBack}
                >
                    取消
                </Button>,
                <Popconfirm
                    title='注意'
                    description='确定要修改吗？'
                    onConfirm={onConfirm}
                    okText='确定'
                    cancelText='取消'
                    key="pop"
                >
                    <Button key="confirm"
                            type="primary"
                    >
                        确定
                    </Button>
                </Popconfirm>
            ]}
        >
            <Row>
                <div style={modalItemStyle}>
                    <Col span={4}><span>名称:</span></Col>
                    <Col span={20}>
                        <Input value={editUser.nickName} onChange={handleInputChange('nickName')}/>
                    </Col>
                </div>
                <div style={modalItemStyle}>
                    <Col span={4}><span>邮箱:</span></Col>
                    <Col span={20}>
                        <Input value={editUser.email} onChange={handleInputChange('email')}/>
                    </Col>
                </div>
                <div style={modalItemStyle}>
                    <Col span={4}><span>生日:</span></Col>
                    <Col span={4}>
                        <Input maxLength={4} value={editDate.year} onChange={handleDateChange('year')}/>
                    </Col>
                    <Col span={1}><span>年</span></Col>
                    <Col span={4}>
                        <Input maxLength={2} value={editDate.monthS} onChange={handleDateChange('monthS')}/>
                    </Col>
                    <Col span={1}><span>月</span></Col>
                    <Col span={4}>
                        <Input maxLength={2} value={editDate.dayS} onChange={handleDateChange('dayS')}/>
                    </Col>
                    <Col span={1}><span>日</span></Col>
                </div>
                <div style={modalItemStyle}>
                    <Col span={4}><span>签名:</span></Col>
                    <Col span={20}>
                        <TextArea
                            autoSize={{
                                minRows: 2,  // 最小行数
                                maxRows: 6   // 最大行数
                            }}
                            value={editUser.signature}
                            onChange={handleInputChange('signature')}
                        />
                    </Col>
                </div>
            </Row>
        </Modal>
    )
}

export default UserModal